#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   crawl_webquery.py    
@Contact :   raogx.vip@hotmail.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2021/12/19 下午8:08   gxrao      1.0         None
'''

# import lib
import copy

from project_setting import image_data_new_path
from utils.table_utils import parse_line_table
from scrapy import selector
import requests
import os
import re
import pytesseract
from PIL import Image

def predict_image(image_url):
    img = Image.open(image_url)
    code = pytesseract.image_to_string(img).strip()
    return code

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'http://webquery.coscoyh.com.cn:8080/yhweb/admin/infoquery/publicQuery.do?queryType=4',
    'User-Agent ': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
}

def save_pic(url, basepath=image_data_new_path,request_cookie=None,headers=None):
    photo = requests.get(url, headers=headers, cookies=request_cookie)
    print(request_cookie)
    save_pic_path = os.path.join(basepath,"webquery")
    if not os.path.exists(save_pic_path):
        os.mkdir(save_pic_path)
    random_str = "2"
    if 'JSESSIONID' in request_cookie:
        random_str = request_cookie["JSESSIONID"]
    filename = os.path.join(save_pic_path, random_str+'.jpg')
    with open(filename, 'wb') as f:
        f.write(photo.content)
    return filename

def find_verlify_code_imageurl(request_html):
    patten = "src=\'/yhweb/imageservlet2\?[^\']*"
    match = re.search(patten,request_html)
    image_url = ""
    image_sn = ""
    if match:
        image_url = "http://webquery.coscoyh.com.cn:8080"+ match[0].replace("src=\'","")
        image_sn = image_url.split("=")[1]

    return image_url,image_sn


def get_tidan_info(billNo,img_sn,img_val,cookies):
    origin_url = "http://webquery.coscoyh.com.cn:8080/yhweb/admin/infoquery/queryPublicQueryRS.do"
    params = {
        "pageDirection":0,
        "pageSize":0,
        "pageIndex":0,
        "queryType":4,
        "cntr":"",
        "order":'asc',
        "shipCode":"",
        "dockenddoc":"",
        "dockendcntr":"",
        "cntr3":"",
        "billNo":"",
        "img_sn":"",
        "img_val":"",
        "queryType5":"total",
        "billNo5":"",
        "cntr5":""
    }

    params['billNo'] = billNo
    params["img_sn"] = img_sn
    params["img_val"] = img_val

    for index, (key,value) in enumerate(params.items()):
        if index == 0:
            origin_url += "?" + key+"="+str(value)
        else:
            origin_url += "&" + key + "=" + str(value)

    print(origin_url)
    nwe_headers = copy.deepcopy(headers)
    nwe_headers["Referer"] = origin_url
    res = requests.get(origin_url,cookies=cookies,headers=nwe_headers)
    sel = selector.Selector(res)
    table_node  = sel.xpath('//table[@id="table4"]')[0]
    result = parse_line_table(table_node)
    return result



def parse_webquery(craw_id):
    search_url = "http://webquery.coscoyh.com.cn:8080/yhweb/admin/infoquery/publicQuery.do?queryType=4"
    res = requests.get(search_url, headers=headers)

    cookies = res.cookies
    cookie = requests.utils.dict_from_cookiejar(cookies)
    print(cookie)

    image_url,image_sn = find_verlify_code_imageurl(res.text)
    saved_url = save_pic(image_url,request_cookie=cookies,headers=headers)

    code = predict_image(saved_url)

    print(code)

    result = get_tidan_info(craw_id,image_sn,code,cookie)
    os.remove(saved_url)
    print(result)
    return result









if __name__ == '__main__':
    # craw_id = "EGLV146101852635"
    # parse_webquery(craw_id)
    print(predict_image("/home/fanfanfeng/project/git_zhou/zhouzian/datas/2.jpg"))